package de.mhu.mandalaui.bind;

import java.io.PrintWriter;
import java.io.StringWriter;

import de.mhu.mandalaui.Component;
import de.mhu.mandalaui.Response;
import de.mhu.mandalaui.Window;

public abstract class Element {

	private String id;
	private Component owner;


	public Element() {
	}
	
	public String getId() {
		if (id == null) doPrepare();
		return id;
	}
	
	public void setId(String id) {
		this.id = id;
	}

	public void doPrepare() {
		if (id == null) {
			id = getWindow().nextId();
		}
			
	}
	
	public Window getWindow() {
		if (owner != null) {
			if (owner instanceof Window) return (Window) owner;
			return owner.getWindow();
		}
		return null;
	}

	public String getBindCall() {
		StringWriter sw = new StringWriter();
		PrintWriter pw = new PrintWriter(sw);
		renderBindCall(pw);
		pw.close();
		return sw.toString();
	}
	
	public void startRender(Response response) {
		response.registerAttribute(this);
	}
	
	public abstract void renderBindCall(PrintWriter out);
	public abstract void renderFunctionImplementation(PrintWriter out);
	public abstract void renderGet(PrintWriter out);
	
	public boolean needFunctionImplementation() {
		return true;
	}
	
	public Component getOwner() {
		return owner;
	}

	public void setOwner(Component owner) {
		if (owner == null) return;
		this.owner = owner;
	}

	public void doRegister(Response response) {
		
	}
	
}
